/* 
    @html filesUpload.index
    @controller
*/
(function () {
  'use strict';
  appModule.controller('filesUpload.index', [
    '$scope', '$q', 'FileUploader', '$http',
    function ($scope, $q, FileUploader, $http) {
      $scope.curChooseNodePath = "";//上传路径

      var fn = function (msg) {
        var deffer = $q.defer();
        deffer.resolve(msg);
        return deffer.promise;
      };

      // zTree配置
      $scope.treeSetting = {
        view: {
          showIcon: false,
          addHoverDom: addHoverDom,
          removeHoverDom: removeHoverDom,
          selectedMulti: false
        },
        edit: {
          enable: true,
          // editNameSelectAll: true,
          showRemoveBtn: showRemoveBtn,
          showRenameBtn: showRenameBtn,
        },
        data: {
          simpleData: {
            enable: true,
            idKey: "path",
            pIdKey: "parent_path",
            rootPId: 0
          }
        },
        callback: {
          // 鼠标左键触发事件
          beforeClick: function (treeId, treeNode, clickFlag) {
            // console.log(treeNode)
            return (treeNode.path !== "//upload-files/"); //上传节点不能点击
          },
          onClick: function (e, treeId, treeNode) {
            fn(treeNode).then(function (treeNode) {
              chooseNode(treeNode); // 选中节点
            });
          },
          beforeEditName: beforeEditName,
          beforeRemove: beforeRemove,
          beforeRename: beforeRename,
          onRemove: onRemove,
          onRename: onRename
        }
      };
      var newCount = 0, log, className = "dark";
      function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
          + "' title='add node' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_" + treeNode.tId);
        if (btn) btn.bind("click", function () {
          newCount += 1;
          var zTree = $.fn.zTree.getZTreeObj("FUzTreeBox");
          var name = "文件夹" + newCount
          var pathId = treeNode['path'] + name + '/'
          console.log(pathId)
          zTree.addNodes(treeNode, { path: pathId, parent_path: treeNode['path'], name: name, new: true });
          return false;
        });
      };
      function removeHoverDom(treeId, treeNode) {
        $("#addBtn_" + treeNode.tId).unbind().remove();
      };
      function beforeEditName(treeId, treeNode) {
        className = (className === "dark" ? "" : "dark");
        showLog("[ " + getTime() + " beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
        var zTree = $.fn.zTree.getZTreeObj("FUzTreeBox");
        zTree.selectNode(treeNode);
        setTimeout(function () {
          // if (confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？")) {
          //   setTimeout(function() {
          //     zTree.editName(treeNode);
          //   }, 0);
          // }
          zTree.editName(treeNode);
        }, 0);
        return false;
      }
      function beforeRemove(treeId, treeNode) {
        className = (className === "dark" ? "" : "dark");
        showLog("[ " + getTime() + " beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
        var zTree = $.fn.zTree.getZTreeObj("FUzTreeBox");
        zTree.selectNode(treeNode);
        return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
      }
      function onRemove(e, treeId, treeNode) {
        showLog("[ " + getTime() + " onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
      }
      function beforeRename(treeId, treeNode, newName, isCancel) {
        className = (className === "dark" ? "" : "dark");
        showLog((isCancel ? "<span style='color:red'>" : "") + "[ " + getTime() + " beforeRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>" : ""));
        if (newName.length == 0) {
          setTimeout(function () {
            var zTree = $.fn.zTree.getZTreeObj("FUzTreeBox");
            zTree.cancelEditName();
            alert("节点名称不能为空.");
          }, 0);
          return false;
        }
        return true;
      }
      function onRename(e, treeId, treeNode, isCancel) {
        treeNode.path = treeNode['parent_path'] + treeNode.name + '/'
        showLog((isCancel ? "<span style='color:red'>" : "") + "[ " + getTime() + " onRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>" : ""));
      }
      function showRemoveBtn(treeId, treeNode) {
        return treeNode.new;
      }
      function showRenameBtn(treeId, treeNode) {
        return treeNode.new;
      }
      function showLog(str) {
        if (!log) log = $("#log");
        log.append("<li class='" + className + "'>" + str + "</li>");
        if (log.children("li").length > 8) {
          log.get(0).removeChild(log.children("li")[0]);
        }
      }
      function getTime() {
        var now = new Date(),
          h = now.getHours(),
          m = now.getMinutes(),
          s = now.getSeconds(),
          ms = now.getMilliseconds();
        return (h + ":" + m + ":" + s + " " + ms);
      }


      // 初始化
      function init() {
        // 获取文件夹的树结构的数据
        $http.get(API_SERVICE_AMBAR + "api/search/tree?query=*%20filename://upload-files/*").then(function (response) {
          // $http.get(API_SERVICE_AMBAR + "api/search/tree?query=*%20filename://ui-upload/*").then(function (response) {
          $scope.treeData = response.data.tree;
          console.log("树结构", $scope.treeData);
          $scope.rootPath = []; //存储文件夹所在的目录
          $scope.treeFolderData = []; //存储文件夹节点
          $scope.treeData.forEach(function (data, index) {
            $scope.rootPath.push(data.path);
            if (data.name == "upload-files") {
              data.name = '上传文件结构'
            } else {
              data.name = '爬取文件结构'
            }
            data.open = true
            var obj = angular.copy(data)
            obj.children = []
            $scope.treeFolderData.push(obj)
            if (data.children.length > 0) {
              checkHasChildren(data.children)
            }

          }, this)
          $(document).ready(function () {
            console.log($scope.treeFolderData)
            $.fn.zTree.init($("#FUzTreeBox"), $scope.treeSetting, $scope.treeFolderData);
            // 默认选中节点
            // var zTree_Menu = $.fn.zTree.getZTreeObj("FUzTreeBox");
            // var curMenu = zTree_Menu.getNodes()[0].children[0];
            // zTree_Menu.selectNode(curMenu);
            // zTree_Menu.setting.callback.onClick(null, zTree_Menu.setting.treeId, curMenu);
          });
        });
      }
      init();

      // 遍历当前节点是否还有子节点并且判断子节点是否是file类型的方法
      function checkHasChildren(treeData) {
        treeData.forEach(function (data, index) {
          if (data.type != 'file') {
            var obj = angular.copy(data)
            obj.children = []
            $scope.treeFolderData.push(obj)
            if (data.children.length > 0) {
              checkHasChildren(data.children)
            }
          }
        }, this)
      };

      // 选中节点进行操作的函数
      function chooseNode(thisNode) {
        // 用户选中文件夹，则将存储位置按钮显示为自定义存储位置，并且关闭自定义存储位置开关
        $scope.customPathSwitch = false;
        // angular.element(document.getElementById('savePathBtn'))[0].innerText = '自定义存储位置';
        // document.getElementById("savePathBtn").innerText = '自定义存储位置';
        console.log(thisNode);
        $scope.customPathSwitch = false;
        $scope.curChooseNode = thisNode;
        console.log($scope.rootPath);
        if ($scope.curChooseNode.type != 'source') { //选中的节点的类型不是source类型
          for (let i = 0; i < $scope.rootPath.length; i++) {
            if ($scope.curChooseNode.path.indexOf($scope.rootPath[i]) >= 0) {
              $scope.curChooseNodePath = $scope.curChooseNode.path.replace($scope.rootPath[i], "");
              $scope.curChooseNodePath = $scope.curChooseNodePath.substring(0, $scope.curChooseNodePath.length - 1);
            }
          }
          console.log($scope.curChooseNodePath);
        } else {
          $scope.curChooseNodePath = "";
        }
      }

      //自定义存储位置的开关
      $scope.customPathSwitch = false;
      // 自定义存储位置
      $scope.customSavePath = function () {
        $scope.customPathSwitch = !$scope.customPathSwitch;
        console.log($scope.customPathSwitch);
        if ($scope.customPathSwitch) { //用户点击了自定义存储位置的按钮
          // angular.element(document.getElementById('savePathBtn'))[0].innerText = '选择已有文件夹';
          document.getElementById("savePathBtn").innerText = '选择已有文件夹';
        } else {
          // angular.element(document.getElementById('savePathBtn'))[0].innerText = '自定义存储位置';
          document.getElementById("savePathBtn").innerText = '自定义存储位置';
        }
      }

      $scope.tags = []; //存放经过处理的标签数据
      $scope.filterTags = []; //存放过滤掉的标签数据
      $http.get(API_SERVICE_AMBAR + "api/tags").then(function (response) {
        console.log("标签类型数据", response.data);
        $scope.tagsFromHttp = response.data;
        for (let i = 0; i < $scope.tagsFromHttp.length; i++) {
          if ($scope.tagsFromHttp[i].type != 'source' && $scope.tagsFromHttp[i].type != 'auto') {
            $scope.filterTags.push($scope.tagsFromHttp[i]);
          }
        }
        // console.log("$scope.filterTags", $scope.filterTags);
        sortOut($scope.filterTags);
        console.log("$scope.tags", $scope.tags);
      });

      // 将标签名称按所属标签类型进行归类
      function sortOut(jsonData) {
        if (jsonData.length > 1) {
          $scope.tagObj = {};
          $scope.tagObj.tagNames = [];
          $scope.tagObj.tagType = jsonData[0].type; //存放数组的第一个标签对象，用来和数组其余的对象进行标签类型的比较
          $scope.tagObj.tagNames.push(jsonData[0].name);
          $scope.tagObj.id = (Math.random() * 10000000).toString(16).substr(0, 4) + '_' + (new Date()).getTime() + '_' + Math.random().toString().substr(2, 5); //生成唯一的编码
          $scope.tags.push($scope.tagObj);
          jsonData.splice(0, 1); //删除此元素

          for (let i = 0; i < $scope.tags.length; i++) {
            for (let j = 0; j < jsonData.length; j++) {
              if ($scope.tags[i].tagType == jsonData[j].type) {
                $scope.tags[i].tagNames.push(jsonData[j].name);
                jsonData.splice(j, 1);
                check($scope.tags[i], jsonData);
              }
            }
          }
          sortOut(jsonData);
        } else if (jsonData.length == 1) {
          $scope.tagObj = {};
          $scope.tagObj.tagNames = [];
          $scope.tagObj.tagType = jsonData[0].type; //存放数组的第一个标签对象，用来和数组其余的对象进行标签类型的比较
          $scope.tagObj.tagNames.push(jsonData[0].name);
          $scope.tagObj.id = (Math.random() * 10000000).toString(16).substr(0, 4) + '_' + (new Date()).getTime() + '_' + Math.random().toString().substr(2, 5); //生成唯一的编码
          $scope.tags.push($scope.tagObj);
          jsonData.splice(0, 1); //删除此元素
          console.log("ok");
          console.log("jsonData", jsonData);
          return false;
        } else {
          return false;
        }
      }

      function check(data_1, data_2) {
        for (let k = 0; k < data_2.length; k++) {
          if (data_1.tagType == data_2[k].type) {
            data_1.tagNames.push(data_2[k].name);
            data_2.splice(k, 1);
            check(data_1, data_2);
          }
        }
      }

      // 记录用户添加的标签
      $scope.addedTags = [];
      $scope.showNotChooseTagName = true; //标记是否显示用户可供选择的标签
      $scope.showChooseTagName = true; //标记是否显示用户已选择的标签
      $scope.fileTag = {}; //空对象，用来存放文件类型
      $scope.specialTag = {}; //空对象，用来存放专题类型
      $scope.tagNamesOfFile = []; //存放用户选择的属于文件类型的标签的数组
      $scope.tagNamesOfSpecial = []; //存放用户选择的属于专题类型的标签的数组
      $scope.newTags = []; //存放用户新增的标签对象
      // 添加文件标签
      $scope.addTagNames = function ($index, tagType, id) {
        this.showNotChooseTagName = !(this.showNotChooseTagName);
        for (let i = 0; i < $scope.tags.length; i++) {
          if (id == $scope.tags[i].id) { //将用户新增的标签归到一类
            $scope.tags[i].tagNames.forEach(function (tagName, index) {
              if ($index == index) {
                $scope.newTag = {};
                $scope.newTag.id = id;
                $scope.newTag.tagName = tagName;
                $scope.newTags.push($scope.newTag);

                // 记录用户添加的标签
                $scope.newAddedTag = {};
                $scope.newAddedTag.tagType = tagType;
                $scope.newAddedTag.tagName = tagName;
                $scope.addedTags.push($scope.newAddedTag);

              }
            })
          }
        }
        console.log("用户新增的标签对象", $scope.newTags);
        console.log("用户添加的标签", $scope.addedTags);
      };

      // 删除文件标签
      $scope.removeTag = function ($index, newTag) {
        this.showChooseTagName = !(this.showChooseTagName);
        for (let i = 0; i < $scope.tags.length; i++) {
          if (newTag.id == $scope.tags[i].id) {
            $scope.newTags.forEach(function (newTag, index) {
              if ($index == index) {
                $scope.tags[i].tagNames.push(newTag.tagName);
                for (let j = 0; j < $scope.addedTags.length; j++) {
                  if (newTag.tagName == $scope.addedTags[j].tagName) {
                    $scope.addedTags.splice(j, 1);
                  }
                }
              }

            })
          }

        }
        console.log("用户添加的标签", $scope.addedTags);
      }

      // 文件上传
      var filesUploader = $scope.filesUploader = new FileUploader({
        url: API_SERVICE_AMBAR + 'api/files/uiupload',
        formData: [{
          fileName: "",
          mkdirPath: "",
          tags: ""
        }]
      });
      filesUploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
      };
      filesUploader.onAfterAddingFile = function (fileItem) {
        console.info('onAfterAddingFile', fileItem);
        console.info('fileTag', $scope.addedTags);
        // console.info('onAfterAddingFile', fileItem.file.name);
      };
      filesUploader.onAfterAddingAll = function (addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
      };
      filesUploader.onBeforeUploadItem = function (item) {
        item.formData[0].fileName = item.file.name;
        item.formData[0].mkdirPath = $scope.curChooseNodePath;
        item.formData[0].tags = JSON.stringify($scope.addedTags);
        console.info('onBeforeUploadItem', item);
      };
      filesUploader.onProgressItem = function (fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
      };
      filesUploader.onProgressAll = function (progress) {
        console.info('onProgressAll', progress);
      };
      filesUploader.onSuccessItem = function (fileItem, response, status, headers) {
        console.info('onSuccessItem', fileItem, response, status, headers);
      };
      filesUploader.onErrorItem = function (fileItem, response, status, headers) {
        console.info('onErrorItem', fileItem, response, status, headers);
      };
      filesUploader.onCancelItem = function (fileItem, response, status, headers) {
        console.info('onCancelItem', fileItem, response, status, headers);
      };
      filesUploader.onCompleteItem = function (fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
      };
      filesUploader.onCompleteAll = function () {
        console.info('onCompleteAll');
      };

      /* 
        自定义文件标签名称
        记录用户点击的标签类型
      */
      $scope.chooseTagType = function (tag) {
        $scope.tagTypeForChoose = tag.tagType;
      }

      $scope.showTagTypeTip = false;
      $scope.showTagNameTip = false;
      // 保存用户自定义的标签名称
      $scope.saveCustomTagName = function () {
        if ($scope.tagTypeForChoose && $scope.customTagName) { //标签类型和标签名称不为空
          for (let i = 0; i < $scope.tags.length; i++) {
            if ($scope.tagTypeForChoose == $scope.tags[i].tagType) { //属于新增的标签类型
              // $scope.tags[i].tagNames.push($scope.customTagName);
              $scope.newTag = {};
              $scope.newTag.id = $scope.tags[i].id;
              $scope.newTag.tagName = $scope.customTagName;
              $scope.newTags.push($scope.newTag);

              $scope.newAddedTag = {};
              $scope.newAddedTag.tagType = $scope.tagTypeForChoose;
              $scope.newAddedTag.tagName = $scope.customTagName;
              $scope.addedTags.push($scope.newAddedTag);
              console.log("用户添加的标签", $scope.addedTags);
              $('#showAddCusTagName').modal('hide');
              $scope.showTagTypeTip = false;
              $scope.showTagNameTip = false;
              // 保存后，清空
              $scope.customTagName = null;
              return false;
            }
          }
          // 新增的标签类型
          $scope.addNewTag = {};
          $scope.addNewTag.id = (Math.random() * 10000000).toString(16).substr(0, 4) + '_' + (new Date()).getTime() + '_' + Math.random().toString().substr(2, 5); //生成唯一编码
          $scope.addNewTag.tagType = $scope.tagTypeForChoose;
          $scope.addNewTag.tagNames = [];
          // $scope.addNewTag.tagNames.push($scope.customTagName);
          $scope.tags.push($scope.addNewTag);

          // 将其显示在已选择的标签栏下面
          $scope.newTag = {};
          $scope.newTag.id = $scope.addNewTag.id;
          $scope.newTag.tagName = $scope.customTagName;
          $scope.newTags.push($scope.newTag);
          console.log("$scope.tags", $scope.tags);

          // 用来记录用户新增的标签类型
          $scope.newAddedTag = {};
          $scope.newAddedTag.tagType = $scope.tagTypeForChoose;
          $scope.newAddedTag.tagName = $scope.customTagName;
          $scope.addedTags.push($scope.newAddedTag);
          console.log("用户添加的标签", $scope.addedTags);
          $('#showAddCusTagName').modal('hide');
          $scope.showTagTypeTip = false;
          $scope.showTagNameTip = false;
        } else if (!$scope.tagTypeForChoose && $scope.customTagName) {
          $scope.showTagTypeTip = true;
          $scope.showTagNameTip = false;
        } else if (!$scope.customTagName && $scope.tagTypeForChoose) {
          $scope.showTagNameTip = true;
          $scope.showTagTypeTip = false;
        } else if (!$scope.tagTypeForChoose && !$scope.customTagName) {
          $scope.showTagTypeTip = true;
          $scope.showTagNameTip = true;
        }
      }

      $scope.cancelCustomTagName = function () {
        $scope.tagTypeForChoose = null;
        $scope.customTagName = null;
        $scope.showTagTypeTip = false;
        $scope.showTagNameTip = false;
        $('#showAddCusTagName').modal('hide');
      }

      $scope.fileDirectory = null; //根目录
      $scope.showDirectoryTip = false;
      // 添加根目录
      $scope.saveFileDirectory = function () {
        // 用户添加的根目录不为空
        if ($scope.fileDirectory) {
          $scope.showDirectoryTip = false;
          $('#showAddDirectory').modal('hide');
          console.log("$scope.fileDirectory", $scope.fileDirectory);
          // 得到用户添加的根目录之后的操作
          var zTree = $.fn.zTree.getZTreeObj("FUzTreeBox");
          var name = $scope.fileDirectory
          var pathId = "//upload-files/" + name + '/'
          // console.log(pathId)
          var treeNode = zTree.getNodes()[0]
          // console.log(treeNode)
          zTree.addNodes(treeNode, { path: pathId, parent_path: "//upload-files/", name: name, new: true });
          // 操作完之后，根目录置空
          $scope.fileDirectory = null;
        } else {
          $scope.showDirectoryTip = true;
        }

      }
      $scope.cancelFileDirectory = function () {
        $scope.fileDirectory = null;
        $scope.showDirectoryTip = false;
        $('#showAddDirectory').modal('hide');
      }


    }
  ]);
})();
